package com.story.api.common.util;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.apache.log4j.Logger;

import java.util.concurrent.TimeUnit;

/**
 * google guava cache缓存短信验证码5分钟
 * Created by Administrator on 2018/02/02
 */
public class MsgCacheUtil {

    private static Logger logger = Logger.getLogger(MsgCacheUtil.class);

    //LRU算法
    private static LoadingCache<String,String> localCache = CacheBuilder.newBuilder()
            .initialCapacity(10000)
            .maximumSize(100000)
            .expireAfterAccess(5, TimeUnit.MINUTES)
            .build(new CacheLoader<String, String>() {
                //默认的数据加载实现,当调用get取值的时候,如果key没有对应的值,就调用这个方法进行加载.
                @Override
                public String load(String s) throws Exception {
                    return "null";
                }
            });

    public static void setKey(String key, String value) {
        localCache.put(key,value);
    }

    public static String getKey(String key) {
        String value = null;
        try {
            value = localCache.get(key);
            if("null".equals(value)){
                return null;
            }
            return value;
        }catch (Exception e) {
            logger.error("localCache get error",e);
        }
        return null;
    }

    public static void delKey(String key) {
        localCache.invalidate(key);
    }
}
